<template>
  <van-button
    :icon="isCollected ? 'star' : 'star-o'"
    :class="{
      collected: isCollected
    }"
    :loading="loading"
    @click="onCollect"
  />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'

export default {
  name: 'CollectArticle',
  components: {},
  model: {
    prop: 'isCollected'
  },
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      loading: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  // 方法集合
  methods: {
    async onCollect() {
      this.loading = true
      try {
        if (this.isCollected) {
          // 已收藏，取消收藏
          await deleteCollect(this.articleId)
        } else {
          // 未收藏，添加收藏
          await addCollect(this.articleId)
        }

        // 更新视图
        // 自定义事件修改数据并不是立即的
        this.$emit('input', !this.isCollected)

        this.$toast.success(this.isCollected ? '取消收藏' : '收藏成功')
      } catch (error) {
        this.$toast.fail('操作失败，请重试！')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.collected {
  .van-icon {
    color: #ffa500;
  }
}
</style>
